<template>
  <div class="detail-page">
    <van-nav-bar left-text="返回" @click-left="$router.back()" fixed title="面经详细" />
    <header class="header">
      <h1>{{ article.stem }}</h1>
      <p>{{ article.createdAt }} |浏览量 {{ article.views }} | 点赞数{{ article.likeCount }}</p>
      <p>
        <img :src="article.avatar" alt />
        <span>{{ article.creator }}</span>
      </p>
    </header>
    <main class="body" v-html="article.content"></main>
    <div class="opt">
      <!-- 点击切换类名，显示是否选上喜欢 -->
      <van-icon name="like-o" :class="{ active: article.likeFlag == true }" @click="toggleLike" />
      <van-icon
        name="star-o"
        :class="{ active: article.collectFlag == true }"
        @click="toggleCollect"
      />
    </div>
  </div>
</template>

<script>
import { getarticleDetailAPI, updateLikeAndCollect } from '@/api/article'
export default {
  name: 'detail-page',
  // 获取数据，渲染到页面
  data () {
    return {
      article: {}
    }
  },
  // 自动执行ajax请求
  async created () {
    // 获取路径里面的id,获取返回数据
    const { data: res } = await getarticleDetailAPI(this.$route.params.id)
    console.log(res)
    this.article = res.data
  },
  methods: {
    // 点击切换类名，发送请求
    async toggleLike () {
      this.article.likeFlag = !this.article.likeFlag
      // 成功和失败添加提示，并增加或减少点赞量
      if (this.article.likeFlag) {
        this.$toast.success('点赞成功')
        this.article.likeCount++
      } else {
        this.$toast.fail('取消点赞')
        this.article.likeCount--
      }
      // 发送请求
      await updateLikeAndCollect({
        id: this.article.id,
        optType: 1
      })
    },
    async toggleCollect () {
      this.article.collectFlag = !this.article.collectFlag
      // 提示收藏成功或失败
      if (this.article.collectFlag) {
        this.$toast.success('收藏成功')
      } else {
        this.$toast.fail('取消收藏')
      }
      // 发送请求
      await updateLikeAndCollect({
        id: this.article.id,
        optType: 2
      })
    }
  }
}
</script>

<style lang="less" scoped>
.detail-page {
  margin-top: 44px;
  overflow: hidden;
  padding: 0 15px;
  .header {
    h1 {
      font-size: 24px;
    }
    p {
      color: #999;
      font-size: 12px;
      display: flex;
      align-items: center;
    }
    img {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      overflow: hidden;
    }
  }
  .opt {
    position: fixed;
    bottom: 100px;
    right: 0;
    > .van-icon {
      margin-right: 20px;
      background: #fff;
      width: 40px;
      height: 40px;
      line-height: 40px;
      text-align: center;
      border-radius: 50%;
      box-shadow: 2px 2px 10px #ccc;
      font-size: 18px;
      &.active {
        background: #fec635;
        color: #fff;
      }
    }
  }
}
</style>
